<?php
/**********************************************************************
 *                                                                    *    
 * Copyright (c) 2009 Dmytro Bezhnar. All rights reserved.     *
 *                                                                    *
 **********************************************************************/

/**
 * Ageset entity manager.
 *
 * @version $Id: CacheBaseManager.php,v 1.2 2008/03/20 14:09:20 sdobrovol Exp $
 */
class CacheBaseManager extends ORMManager  
{

	function set_cache($name,$value='') {
		$this->dialog->cache[$name] = $value;
	}
	
	function check_cache($name = '') {
		if (!$GLOBALS['options']['memcache']['enable']) {
			$this->check_cache_memcache($name);
		} else {
			$this->check_cache_db($name);
		}
	}
	
	function check_cache_memcache($name = '') {
		$qs = $this->getQuery()->from('CacheDBO');
		if ($name != '') $qs->where("name = '$name'");
		$data = $qs->useResultCache(true,$GLOBALS['options']['memcache_core']['cache_arr_time'])->fetchArray();
		foreach ($data as $item) {
			//$this->set_cache($item['name'],$item['value']);
			if ($item['exec_only']) {
					$memcached = parent::$cacheDriver;
					$data= $memcached->fetch($this->getMemcacheName($item['sql_to_calculate'],''));
			   		if ($data === false ) {
						$arr = explode(';', $item['sql_to_calculate']);
						foreach ($arr as $val){
							$this->getQuery()->parseQuery($val)->execute();
						}
						$memcached->save($this->getMemcacheName($item['sql_to_calculate'],''),array(),$item['recheck_period'],'');
			   		}
			} else {
				$value_arr = $this->getQuery()->parseQuery($val)->fetchOne()->toArray();
				$value = $value_arr['count']; 
				$this->set_cache($item['name'],$value);
			}
		}
	}
	
	function check_cache_db($name = '') {
		$qs = $this->getQuery()->select('*, (DATE_ADD(check_time, INTERVAL recheck_period SECOND) > NOW()) as cache_actual')->from('CacheDBO');
		if ($name != '') $qs->where("where name = '$name'");
		$data = $qs->fetchArray();
		
		foreach ($data as &$item) {
			if ($item['cache_actual'] > 0) {
				$this->set_cache($item['name'],$item['value']);
			} else {
				if ($item['exec_only']) {
					$arr = explode(';', $item['sql_to_calculate']);
					foreach ($arr as $val){
						$this->getQuery()->query($val)->execute();
					}
					$value = $item['value'];
				} else {
					$value_arr = $this->getQuery()->parseQuery($item['sql_to_calculate'])->fetchOne()->toArray();
					$value = $value_arr['count']; 
					$this->set_cache($item['name'],$value);	
					$value = $this->dialog->checkTextForMysql($value);
				}
				$this->getQuery()->update('CacheDBO')->set('value',$value)->set('check_time','now()')->where("name = '".$item['name']."'")->execute();
			}
		}
		
	}
}
?>